package com.liholin.springboot.sample.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class AssignmentUtils {

    /**
     * 该方法 主要用于 如果bObject中某个属性为null 就将aObject的属性值进行赋值给bObject的该属性值
     * 该两个Object为同属一个实体类或者aObject的所有属性必须包括bObject的所有属性
     * @param aObject 实体类对象
     * @param bObject 实体类对象
     */
    public static void entityClassAssignment(Object aObject,Object bObject){
        for (Field bField : bObject.getClass().getDeclaredFields()) {
            bField.setAccessible(true);
            try {
                Field aField = aObject.getClass().getDeclaredField(bField.getName());
                aField.setAccessible(true);
                if (bField.get(bObject) == null) {
                    bField.set(bObject, aField.get(aObject));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 判断对象中的值是否都为空
     */
    public static boolean fieldIsAllEmpty(Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        List<Boolean> mList = new ArrayList<>();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object o = field.get(object);
                if (o == null || o instanceof String && StringUtils.isEmpty((String) o)) {
                    mList.add(true);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return mList.size() == fields.length;
    }
}
